package com.jxw.cloudpen.web.websockethandler;

import com.jxw.cloudpen.web.netty.Entity.StreamData;
import com.jxw.cloudpen.web.netty.common.LocalSession;
import com.jxw.cloudpen.web.netty.common.SessionManger;
import com.jxw.cloudpen.web.netty.google.InfiniteStreamRecognize6;
import com.jxw.cloudpen.web.netty.google.StreamRecognManager;
import com.jxw.cloudpen.web.netty.util.ByteObjUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LoginRequestHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(LoginRequestHandler.class);
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    /**
     * 收到消息
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if (null == msg || !(msg instanceof StreamData)) {
            super.channelRead(ctx, msg);
            return;
        }

        StreamData message = (StreamData) msg;
        if (!message.getType().equals(0)) {
            super.channelRead(ctx, msg);
            return;
        }
        //登录功能
        LocalSession session = new LocalSession(ctx.channel());

        //登录默认通过
        //数据放到管道上，可共享
        ctx.channel().attr(LocalSession.SESSION_KEY).set(session);
        /**
         * 通知客户端：登录成功
         */
        if ("test".equals(message.getSecretKey())) {
            StreamData result = new StreamData();
            result.setClientId(session.getClientId());
            result.setType(1);
            ctx.channel().writeAndFlush(ByteObjUtil.objToBytes(result));
            ctx.pipeline().remove(LoginRequestHandler.this);
            log.info("登录成功:" + session.getClientId());


            executorService.submit(()-> {
                try {
                    InfiniteStreamRecognize6 infiniteStreamRecognize6 = new InfiniteStreamRecognize6();
                    StreamRecognManager.map.put(session.getClientId(),infiniteStreamRecognize6);
                    infiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
//                InfiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
                } catch (Exception e) {
                    System.out.println("Exception caught: " + e);
                }
            });
            Thread.sleep(1000);


            SessionManger.addLocalSession(session);
        } else {
            SessionManger.closeSession(ctx);
            log.info("登录失败:" + session.getUser());
        }
    }


}
